package com.cuitrip.business.search;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.cuitrip.apiservice.SearchBusiness;
import com.cuitrip.apiservice.TrackBusiness;
import com.cuitrip.business.home.travel.TravelTripListActivity;
import com.cuitrip.business.home.travel.model.Destination;
import com.cuitrip.business.home.travel.model.PopupFilterItem;
import com.cuitrip.business.home.travel.model.SelectInfo;
import com.cuitrip.business.search.model.HotSearch;
import com.cuitrip.business.track.TrackProxy;
import com.cuitrip.component.flowlayout.TagView;
import com.cuitrip.service.R;
import com.cuitrip.util.FlowLayout;
import com.lab.app.BaseActivity;
import com.lab.component.list.CTRecyclerView;
import com.lab.component.list.simple.CTSimpleRecyclerAdapter;
import com.lab.component.list.simple.CTSimpleViewHolder;
import com.lab.jumper.Jumper;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.utils.DisplayUtil;
import com.lab.utils.MessageUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 搜索页面 activity
 * Created  ak
 */
public class SearchActivity extends BaseActivity implements IProxyCallback {


    @Bind(R.id.search_box)
    protected EditText searchBox;

    @Bind(R.id.ct_recycler_view)
    CTRecyclerView mCtRecyclerView;

    private CTSimpleRecyclerAdapter mAdapter;

    private List<Destination> destinationList = new ArrayList<>();

    private String mQuery;
    private ApiProxy mApiProxy;
    private FlowLayout mFlowLayout;


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_search_view);
        ButterKnife.bind(this);
        TrackProxy.getInstance().reviewPage(TrackBusiness.Source.HOT_SEARCH, "");
        mApiProxy = new ApiProxy(this);
        mFlowLayout = new FlowLayout(this);
        requestHotWords();
        searchBox.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if ((event == null || event.getAction() == KeyEvent.ACTION_UP)
                        && (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_GO || actionId == EditorInfo.IME_ACTION_UNSPECIFIED || actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT)) {
                    TrackProxy.getInstance().searchWords(TrackBusiness.Source.HOT_SEARCH, searchBox.getText().toString(), "");
                    requestSearch(searchBox.getText(), searchBox.getText().toString(), false);
                }
                return true;
            }
        });

        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mCtRecyclerView.setLayoutManager(mLayoutManager);
        mAdapter = new CTSimpleRecyclerAdapter<Destination>(this, destinationList) {
            @Override
            public int getItemLayoutId(int viewType) {
                return R.layout.ct_layout_filter_item;
            }

            @Override
            public void onNewViewHolder(CTSimpleViewHolder viewHolder, ViewGroup parent, int viewType) {

            }

            @Override
            public void bindData(CTSimpleViewHolder holder, final int position, final Destination item) {
                FlowLayout flowLayout = holder.getView(R.id.flow_layout);
                TextView categoryText = holder.getView(R.id.tv_category);
                categoryText.setText(item.getCategoryTitle());

                flowLayout.setMaxCountinLine(3);
                flowLayout.setHorizontalSpacing(DisplayUtil.dip2px(20));
                List<Destination.Value> filterItemList = item.getList();
                for (int i = 0; i < filterItemList.size(); i++) {
                    final PopupFilterItem popupFilterItem = filterItemList.get(i);
                    if (popupFilterItem.isShow()) {
                        TagView tagView = new TagView(SearchActivity.this, popupFilterItem.getKey());
                        tagView.setBackgroundResource(R.drawable.select_white_corner);
                        tagView.setTextColor(getResources().getColorStateList(R.color.ct_white_qiaomai));
                        tagView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                requestSearch(popupFilterItem.getValue(), popupFilterItem.getKey(), true);

                            }
                        });
                        flowLayout.addView(tagView);
                    }
                }


            }
        };


        mCtRecyclerView.setAdapter(mAdapter);


    }

    private void requestSearch(CharSequence charSequence, String title, boolean city) {
        String q = charSequence.toString().trim();
        mQuery = q;
        if (TextUtils.isEmpty(q)) {
            return;
        }
        Intent intent = new Intent(this, TravelTripListActivity.class);
        if (city) {
            intent.putExtra(SelectInfo.CITY_KEY, mQuery);
            intent.putExtra(SelectInfo.KEY_FROM, SelectInfo.FROM_HOME_CARD);
        } else {
            intent.putExtra(SelectInfo.KEY_WORD_KEY, mQuery);
            intent.putExtra(SelectInfo.KEY_FROM, SelectInfo.FROM_SEARCH);
        }
        intent.putExtra(SelectInfo.TITLE_KEY, title);
        Jumper.launchActivity(this, intent);
    }

    private void requestHotWords() {
        SearchBusiness.getHotDestinationList(mApiProxy);
    }

    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        CtApiResponse response = (CtApiResponse) result.getData();
        if (response.isResponseNormal()) {
            if (response.result instanceof HotSearch) {
                List<Destination> destinationList = ((HotSearch) response.result).getDestExp();
                inflateList(destinationList);
            }
        } else {
            if (response != null && !TextUtils.isEmpty(response.msg)) {
                MessageUtils.showToast(response.msg);
            }
        }
        return false;
    }


    private void inflateList(List<Destination> tempList) {
        mAdapter.setDataList(tempList);
    }


    @OnClick(R.id.cancel_action)
    public void cancelSearch() {
        finish();
    }


}
